package com.xiaojie.service;

import com.xiaojie.entity.Permission;
import com.xiaojie.entity.User;
import com.xiaojie.mapper.PermissionMapper;
import com.xiaojie.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author HTGY02
 * @Date 2021/4/28 10:57
 * @Version 1.0
 **/
@Service
@Slf4j
public class UserService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByName(username);
        if (user == null) {
            //如果用户为空 返回null
            return null;
        }
        //不为空，讲权限列表查出，赋值给user
        List<Permission> listPermission = permissionMapper.listAll(username);
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        listPermission.forEach( permission -> {
            authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
        });
        log.info(">>>authorities:{}<<<", authorities);
        //将权限赋值给用户
        user.setAuthorities(authorities);
        return  user;
    }
}
